import {withLoading} from 'utils/dva';
import services from '../../services';
import model from '../model';
import {pageConfig} from 'configs/constants';

const defaultConfig = {
  pagination: {
    ...pageConfig,
    total: 0
  },
  list: []
};


export default model.extend({

  namespace: 'articleCategory',

  state: {
    config: defaultConfig,
    user: [],
    loading: {
      list: false,
      add: false,
      del: false
    }
  },

  subscriptions: {
    setup({dispatch, history}) {
      // 监听路由的变化，请求页面数据
      return history.listen(({pathname}) => {
        let list = [];
        if (pathname === '/article/category') {
          dispatch({type: 'getList', payload: {list}});
        }
      });
    }
  },

  effects: {
    * getList({payload}, {call, select, update}) {
      const {config: {pagination}} = yield select(({articleCategory}) => articleCategory);
      const {pageSize, current} = pagination;
      const {data} = yield call(withLoading(services.article.getCategoryList, 'list'),
          {ps: pageSize, pn: current, ...payload});
      yield update({
        config: {
          list: data.list,
          pagination: {
            ...pagination,
            total: data.total
          }
        }
      });
    },
    * add({payload}, {call}) {
      yield call(withLoading(services.article.categoryAdd, 'add', '新增成功'), {...payload});
    },
    * edit({payload}, {call}) {
      yield call(withLoading(services.article.categoryEdit, 'add', '更新成功'), {...payload});
    }
  },

  reducers: {
    goPage(state, {payload}) {
      return {
        ...state,
        config: {
          ...state.config,
          pagination: {
            ...state.config.pagination,
            current: payload
          }
        }
      };
    }
  }

});
